/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.ventas;

import dp1.titandevelop.titano.bean.Estado;
import dp1.titandevelop.titano.bean.FiltroNC;
import dp1.titandevelop.titano.view.*;
import dp1.titandevelop.titano.persistent.DetalleDamanda;
import dp1.titandevelop.titano.persistent.Distribuidor;
import dp1.titandevelop.titano.persistent.NotaCredito;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.service.DemandaService;
import dp1.titandevelop.titano.service.DistribuidorService;
import dp1.titandevelop.titano.service.NotaCreditoService;
import dp1.titandevelop.titano.service.ValidacionService;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author heli
 */
public class BusquedaNotaCredito extends javax.swing.JDialog {
public Integer idNotaCredito;
public Float notacredito;
public String estoy="notacredito";
public List<NotaCredito> listaNotasCredito = new ArrayList<NotaCredito>();
    
    public BusquedaNotaCredito(java.awt.Frame parent, boolean modal,String distribuidor) {
        super(parent, modal);
        initComponents();
        Estado state=new Estado();
        ValidacionService validacionService = new ValidacionService();
        
        NotaCreditoService service=new NotaCreditoService();
        FiltroNC filtro=new FiltroNC();
        filtro.setRazonSocial(distribuidor);
        filtro.setEstado(state.getSinUsar());
       this.listaNotasCredito=service.buscarNotaCredito(filtro);
        this.inhabilitaBotones();
        this.actualizarNotaCreditoList();
    }
    
    public void habilitaBotones(){
        this.btnOk.setEnabled(true);
    }
    private void inhabilitaBotones(){
        this.btnOk.setEnabled(false);
    }
    
Thread actualizarnotacredito = null;
    private void actualizarNotaCreditoList(){
        if( actualizarnotacredito!=null && actualizarnotacredito.isAlive() ){
            actualizarnotacredito.interrupt();
        }
        actualizarnotacredito = new Thread( new Runnable() {
            @Override
            public void run() {
                buscarDistribuidor();
                RefreshTable();
                ModeloTabla modelo= new ModeloTabla();
                tablaResultados.setModel(modelo);
                
            }
        });
        actualizarnotacredito.start();
    }
    
     public void RefreshTable() {
        
        AbstractTableModel aux = (AbstractTableModel)tablaResultados.getModel();
        aux.fireTableDataChanged();
    }
    
     public void buscarDistribuidor(){
         
         DistribuidorService p=new DistribuidorService();
        ModeloTabla modelo= new ModeloTabla();
        tablaResultados.setModel(modelo);
     }
     
    class ModeloTabla extends AbstractTableModel {  
        //Atributos de los datos de la tabla
        private String [] titles = {"Fecha","Descripción","Motivo","Monto"};
        //private List<DataTabla> datos;
        //private Object [][]datos;
        
        public int getRowCount() {
            return listaNotasCredito.size();//tipos.size(); // cuantos registros (filas)
        }      
        
        public int getColumnCount() {
            return 4; // cuantas columnas
        }          
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }                
       
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object resultado=null;
            NotaCredito d = listaNotasCredito.get(rowIndex);
            switch(columnIndex){
                case 0: resultado = d.getFecha(); break;
                case 1: resultado = d.getDescripcion(); break;
                case 2: if(d.getTipo()==1) resultado = "Anulación Factura"; else resultado = "Devolución";  break;
                case 3: resultado = d.getMonto(); break;    
                
            }
            return resultado;
        } 
        //Ultima celda editable para selección
       
        //para obtener las clases de cada celda y asi mostrar estas correctamente
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel6 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaResultados = new javax.swing.JTable();
        btnOk = new javax.swing.JButton();
        btnCancelar1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Notas de Crédito", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("")), "Notas de Crédito"));

        tablaResultados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Fecha", "Descripción", "Motivo", "Monto"
            }
        ));
        tablaResultados.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaResultadosMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tablaResultados);

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(14, Short.MAX_VALUE))
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/asignar.png"))); // NOI18N
        btnOk.setToolTipText("Agregar");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        btnCancelar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/retroceder.png"))); // NOI18N
        btnCancelar1.setToolTipText("Cancelar");
        btnCancelar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelar1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                        .addComponent(btnOk)
                        .addGap(0, 0, 0)
                        .addComponent(btnCancelar1)))
                .addGap(8, 8, 8))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOk)
                    .addComponent(btnCancelar1))
                .addGap(8, 8, 8))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tablaResultadosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaResultadosMouseClicked
        if(evt.getClickCount()==1){
            NotaCredito seleccionado;
            seleccionado = listaNotasCredito.get(this.tablaResultados.getSelectedRow());
            this.idNotaCredito=Integer.valueOf(seleccionado.getIdnotacredito());
            notacredito=seleccionado.getMonto();
            this.habilitaBotones();
            this.dispose();
        }

        // TODO add your handling code here:
    }//GEN-LAST:event_tablaResultadosMouseClicked

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed

        this.dispose();
    }//GEN-LAST:event_btnOkActionPerformed

    private void btnCancelar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelar1ActionPerformed
        this.idNotaCredito=0;
        this.dispose();
    }//GEN-LAST:event_btnCancelar1ActionPerformed

    /**
     * @param args the command line arguments
     */
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar1;
    private javax.swing.JButton btnOk;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tablaResultados;
    // End of variables declaration//GEN-END:variables
}
